import { NextFunction, Request, Response } from 'express'
import jwt from 'jsonwebtoken'

import { IUser } from '../types/user'

declare global {
  namespace Express {
    interface Request {
      user?: IUser
    }
  }
}

export const authMiddleware = (req: Request, res: Response, next: NextFunction) => {
  const token = req.header('Authorization')?.replace('Bearer ', '')

  if (!token) {
    return res.status(401).json({
      code: 401,
      message: '请先登录',
    })
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET!) as IUser
    req.user = decoded
    next()
  } catch (err) {
    res.status(401).json({
      code: 401,
      message: '无效的Token',
    })
  }
}
